const { dialog } = require('electron')
const fs = require('fs');
const Extract = require('./unzipper/extract.cjs');

async function selectFileAsync() {
    const { canceled, filePaths } = await dialog.showOpenDialog({})
    if (!canceled) {
        console.log(filePaths[0])
        return filePaths[0]
    }
    return null
}

async function selectFolderAsync() {
    const result = await dialog.showOpenDialog({
        properties: ['openDirectory']
    })
    if (!result.canceled) {
        console.log(result.filePaths[0])
        return result.filePaths[0]
    }
    return null
}

function unzipAsync(event, arg) {
    return new Promise((resolve, reject) => {
        // 确保输出目录存在  
        fs.mkdirSync(arg.outputDir, { recursive: true });

        // 读取 ZIP 文件并解压  
        fs.createReadStream(arg.zipFilePath)
            .pipe(Extract({ path: arg.outputDir }))
            .on('close', function () {
                console.log('unzip success!');
                resolve(); // 在解压完成时解析 Promise  
            })
            .on('error', function (err) {
                console.error('unzip error:', err);
                reject(err); // 在发生错误时拒绝 Promise  
            });
    });
}

module.exports.selectFileAsync = selectFileAsync;
module.exports.unzipAsync = unzipAsync;
module.exports.selectFolderAsync = selectFolderAsync;